let dao = require('../database/dao'),
  logger = require('../helper/logger'),
  tagLogger = new logger.TagLogger('ARTICLE_MODEL'),
  errorCode = require('../../conf/errorCode'),
  commonModel = require('./commonModel'),
  util = require('../helper/util'),
  _ = require('lodash');

let {
  genUpdateCallback,
  genInsertCallback,
  genUpdateRslt,
  genUpdateBatchRslt,
  genUpdateBatchCallback,
  genSelectCallback,
  genPagination,
  genInertRslt,
} = commonModel;

//创建文章
exports.add = function(articleObj, callback) {
  dao.insert('post', articleObj, genInsertCallback(callback));
};

exports.addPostForUser = function(articleObj, callback) {
  dao.insert('post', articleObj, genInsertCallback(callback));
};
exports.updatePost = function(postId, data, callback) {
  let str = 'UPDATE post SET ',
    k = [],
    v = [];
  _.forEach(data, function(value, key) {
    k.push(key + ' = ?');
    v.push(value);
  });
  v.push(postId);
  str = str + k.join(',');
  str = str + ' where id = ? and status = 0';
  dao.all(str, v, callback);
};

//获取文章列表
exports.getPostByPage = function(channel, page, size, callback) {
  let [offset, limit] = util.ps2ol(page, size),
    fromJoinWhere = `FROM post as p 
                        JOIN category as c
              		    ON p.categoryId = c.id 
                        JOIN user as u
              		    ON p.authorId = u.id 
                        left join 
		            (select id,content,object_id,uid,reply_id,count(*) count,status,ctime  from comments c where c.status>=0 GROUP BY object_id )cm
			on cm.object_id=p.id
                                where p.status >= 0 and p.channel=${channel}`;
  let postQuery = {
    str: `SELECT p.id articleId,p.title articleTitle,p.ctime createTime,p.authorId,u.accountName authorName,c.name categoryName,cm.count commentCount ${fromJoinWhere} order by p.updateAt desc LIMIT ?,? `,
    param: [offset, limit],
  };
  let countQuery = {
    str: `SELECT count(1) as count ${fromJoinWhere}`,
    param: [],
  };
  let queryArr = [postQuery, countQuery];
  dao.queryBatch(queryArr, (err, rslts) => {
    if (err == null)
      callback(null, genPagination(rslts[0], page, size, rslts[1][0].count));
    else callback(err, null);
  });
};

//删除文章-支持批量删除
exports.deletePostByIds = function(ids, callback) {
  dao.deleteBatch('post', ids, callback);
};

//获取文章
exports.getPostById = function(postId, callback) {
  dao.query(
    `SELECT p.id postId, p.title title, p.content content,p.channel channel,p.carIds carIds, p.ctime createTime,p.videoInfo videoInfo, c.id categoryId, c.name categoryName, u.id authorId, u.accountName authorName,pl.id pollId
                FROM post p
                    LEFT JOIN category c ON p.categoryId = c.id 
                    LEFT JOIN polls pl ON pl.postId = p.id 
                    LEFT JOIN user u ON p.authorId = u.id 
                        WHERE p.id = ? AND p.status = 0
                   ORDER BY p.id ASC`,
    [postId],
    //genSelectCallback(callback),
    callback,
  );
};

//获取文章分类
exports.getPostCategory = function(callback) {
  dao.all(`select * from category`, [], callback);
};
